package com.lzx.iteam;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.lzx.iteam.adapter.ChatGroupMemberAdapter;
import com.lzx.iteam.bean.ChatContact;
import com.lzx.iteam.widget.gridimg.AllEasyGridView;
import com.lzx.iteam.widget.gridimg.EasyGridView;
import com.lzx.iteam.widget.gridimg.ImageAdapter;
import com.lzx.iteam.widget.gridimg.MyGridView;
import com.lzx.iteam.net.*;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.util.AllDialogUtil;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Discussion;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by shijunting on 15-3-10.
 * 聊天小组详情页面
 */
public class ChatGroupDetailActivity extends Activity implements View.OnClickListener, EasyGridView.IHandleGridView {

    private LinearLayout mLlBtnBack;
    private RelativeLayout mRlChatGroupName, mRlChatGroupNotify, mRlChatGroupClear, mRlChatGroupDissolve;
    private LinearLayout mNormalMember, mCreaterMember;
    private LinearLayout mSingleChatNameGone, mSingleChatClearGone, mSingleChatDissolveGone;
    private View mSingleChatLineGone;
    private TextView mTvChatGroupName, mTvChatGroupDisband, mTvChatGroupMember;
    private ToggleButton mTbChatGroupNotify;
    private MyGridView mGvChatGroupMember;
    private AllEasyGridView mAegvChatGroupMember;

    public static final int REQUEST_NEW_GROUP_NAME = 3825;
    private ChatGroupMemberAdapter adapter1;
    private ArrayList<ChatContact> mChatContacts;

    private PreferenceUtil mPreferenceUtil;
    private String targetId;
    private String createId;
    private String loginid;
    private String mGroupName;
    private List<String> uids;
    private Discussion mDiscussion;

    private boolean isCreated;
    private boolean isSingle;// 是否是单聊
    private Conversation.ConversationType mConversationType;
    private CloudDBOperation cloudDBOperation;

    private final int MSG_CHAT_USER_INFO = 1000;
    private final int ADD_MEMBER_REQUEST_CODE = 1001;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_CHAT_USER_INFO:
                    if (msg.arg1 == 0) {
                        mChatContacts.clear();
                        mChatContacts.addAll((ArrayList<ChatContact>) msg.obj);
                        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
                        if (mChatContacts != null) {
                            for (int i = 0; i < mChatContacts.size(); i++) {
                                ChatContact chatContact = mChatContacts.get(i);
                                HashMap<String, Object> map = new HashMap<String, Object>();
                                map.put("text", chatContact.getUserName());
                                map.put("icon", chatContact.getUserImg());
                                map.put("user_id", chatContact.getUserId());
                                list.add(map);
                            }
                        }

                        // 单聊
                        if (isSingle) {
                            if (mChatContacts.size() > 0 && mChatContacts != null) {
                                adapter1 = new ChatGroupMemberAdapter(ChatGroupDetailActivity.this);
                                adapter1.bindData(mChatContacts, "发起群聊");
                                mGvChatGroupMember.setAdapter(adapter1);
                            }
                        } else {  // 群聊
                            if (isCreated) {  // 管理者
                                ImageAdapter adapter = new ImageAdapter(ChatGroupDetailActivity.this, true);
                                mAegvChatGroupMember.initData(false, list, adapter);
                                mAegvChatGroupMember.setHandleGridView(ChatGroupDetailActivity.this);
                            } else {
                                if (mChatContacts.size() > 0 && mChatContacts != null) {
                                    adapter1 = new ChatGroupMemberAdapter(ChatGroupDetailActivity.this);
                                    adapter1.bindData(mChatContacts, "添加");
                                    mGvChatGroupMember.setAdapter(adapter1);
                                }
                            }
                        }

/*                        if ("1".equals(mType)) {
//                            mSingleChatClearGone.setVisibility(View.GONE);
                            mSingleChatNameGone.setVisibility(View.GONE);
                            mSingleChatLineGone.setVisibility(View.GONE);
                            mNormalMember.setVisibility(View.VISIBLE);
                            mCreaterMember.setVisibility(View.GONE);
                            mTvChatGroupDisband.setText("删除对话");
                        } else if ("0".equals(mType)) {
//                            mSingleChatClearGone.setVisibility(View.VISIBLE);
                            mSingleChatNameGone.setVisibility(View.VISIBLE);
                            mSingleChatLineGone.setVisibility(View.VISIBLE);
                            if ("1".equals(mUserType)) {//普通成员
                                mNormalMember.setVisibility(View.VISIBLE);
                                mCreaterMember.setVisibility(View.GONE);
                                mTvChatGroupDisband.setText("删除并退出");
                            } else if ("2".equals(mUserType)) {//创建者
                                mCreaterMember.setVisibility(View.VISIBLE);
                                mNormalMember.setVisibility(View.GONE);
                            }
                        }*/
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(ChatGroupDetailActivity.this, R.string.active_failure_no_network,
                                  Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(ChatGroupDetailActivity.this, (String) msg.obj,
                                  Toast.LENGTH_LONG).show();
                        }
                    }
                    break;

            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_group_detail_layout);
        getIntentData();
        initViews();
        mChatContacts=new ArrayList<>();
        cloudDBOperation = new CloudDBOperation(this);
        SealAppContext.getInstance().pushActivity(this);
        if (isSingle) {
            initDatas();
        } else {
            RongIM.getInstance().getDiscussion(targetId, new RongIMClient.ResultCallback<Discussion>() {
                @Override
                public void onSuccess(Discussion discussion) {
                    Log.d("getDiscussion", "onSuccess");
                    mDiscussion = discussion;
                    if (mDiscussion != null) {
                        initDatas(mDiscussion);
                    }
                }

                @Override
                public void onError(RongIMClient.ErrorCode e) {
                    Log.d("getDiscussion", "onError=" + e);

                }
            });

        }

    }


    @Override
    protected void onResume() {
        super.onResume();
    }


    private void getIntentData() {
        Intent intent = getIntent();
        targetId = intent.getStringExtra("TargetId");
        isSingle = intent.getBooleanExtra("isSingle", true);
        mPreferenceUtil = PreferenceUtil.getInstance(this);
        loginid = mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "－1");
        if (isSingle) {
            mConversationType = Conversation.ConversationType.PRIVATE;
        } else {
            mConversationType = Conversation.ConversationType.DISCUSSION;
        }
    }

    private void initViews() {
        mLlBtnBack = (LinearLayout) findViewById(R.id.chat_group_btn_back);
        mRlChatGroupName = (RelativeLayout) findViewById(R.id.rl_chat_group_name);
        mRlChatGroupNotify = (RelativeLayout) findViewById(R.id.rl_chat_group_notify);
        mRlChatGroupClear = (RelativeLayout) findViewById(R.id.rl_chat_group_clear);
        mRlChatGroupDissolve = (RelativeLayout) findViewById(R.id.rl_chat_group_dissolve);
        mNormalMember = (LinearLayout) findViewById(R.id.chat_group_user);
        mCreaterMember = (LinearLayout) findViewById(R.id.chat_group_creator);
        mTvChatGroupName = (TextView) findViewById(R.id.tv_chat_group_name);
        mTvChatGroupMember = (TextView) findViewById(R.id.tv_chat_group_member);
        mTvChatGroupDisband = (TextView) findViewById(R.id.disband_chat_group);
        mTbChatGroupNotify = (ToggleButton) findViewById(R.id.tb_chat_group_notify);
        mGvChatGroupMember = (MyGridView) findViewById(R.id.gv_chat_group_member);
        mAegvChatGroupMember = (AllEasyGridView) findViewById(R.id.aegv_chatgroup_member);
        mSingleChatNameGone = (LinearLayout) findViewById(R.id.single_chat_name_gone);
        mSingleChatClearGone = (LinearLayout) findViewById(R.id.single_chat_clear_gone);
        mSingleChatDissolveGone = (LinearLayout) findViewById(R.id.single_chat_dissolve_gone);
        mSingleChatLineGone = findViewById(R.id.single_chat_line);
        mGvChatGroupMember.setSelector(new ColorDrawable(Color.TRANSPARENT));
        mRlChatGroupDissolve.setOnClickListener(this);
        mRlChatGroupClear.setOnClickListener(this);
        mLlBtnBack.setOnClickListener(this);
        mRlChatGroupName.setOnClickListener(this);
        mRlChatGroupNotify.setOnClickListener(this);
        mGvChatGroupMember.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if ("添加".equals(((ChatContact) adapter1.getItem(position)).getUserName()) || "发起群聊".equals(((ChatContact) adapter1.getItem(position)).getUserName())) {
                    Intent intent = new Intent(ChatGroupDetailActivity.this, ChooseContactByTeamActivity.class);
                    intent.putExtra("member", mChatContacts);
                    intent.setAction("create_chat_group");
                    intent.putExtra("isSingle", isSingle);
                    if (!isSingle) {
                        intent.putExtra("chat_group_id", targetId);
                    }
                    startActivity(intent);
                }
            }
        });

    }

    private void initDatas() {
        mSingleChatNameGone.setVisibility(View.GONE);
        mSingleChatLineGone.setVisibility(View.GONE);
        mNormalMember.setVisibility(View.VISIBLE);
        mCreaterMember.setVisibility(View.GONE);
        mTvChatGroupDisband.setText("删除对话");
        uids = new ArrayList<>();
        uids.add(loginid);
        uids.add(targetId);
        StringBuilder sb = new StringBuilder();
        for (String id : uids) {
            sb.append(id).append(",");
        }
        String ids = sb.toString();
        if (ids != null) {
            getChatUserInfo(ids.substring(0, ids.length() - 1));
        }
    }

    private void initDatas(Discussion mDiscussion) {
//            mSingleChatClearGone.setVisibility(View.VISIBLE);
        mSingleChatNameGone.setVisibility(View.VISIBLE);
        mSingleChatLineGone.setVisibility(View.VISIBLE);
        mTvChatGroupMember.setText("聊天组成员(" + mDiscussion.getMemberIdList().size() + ")");
        createId = mDiscussion.getCreatorId();
        mGroupName = mDiscussion.getName();
        mTvChatGroupName.setText(mGroupName);
        if (loginid.equals(createId)) {
            isCreated = true;
        }
        uids = mDiscussion.getMemberIdList();
        StringBuilder sb = new StringBuilder();
        for (String id : uids) {
            sb.append(id).append(",");
        }
        final String ids = sb.toString();
        if (ids != null) {
            final ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
            new AsyncTask<String, Void, ArrayList<ChatContact>>() {

                @Override
                protected ArrayList<ChatContact> doInBackground(String... params) {

                    for (int i = 0; i < uids.size(); i++) {
                        mChatContacts.clear();
                        ChatContact chatContact = cloudDBOperation.findUserMsgById(uids.get(i));
                        mChatContacts.add(chatContact);
                        HashMap<String, Object> map = new HashMap<String, Object>();
                        map.put("text", chatContact.getUserName());
                        map.put("icon", chatContact.getUserImg());
                        map.put("user_id", chatContact.getUserId());
                        list.add(map);
                    }

                    return mChatContacts;
                }

                @Override
                protected void onPostExecute(ArrayList<ChatContact> chatContacts) {
                    super.onPostExecute(chatContacts);
                        if (isCreated) {  // 管理者
                            ImageAdapter adapter = new ImageAdapter(ChatGroupDetailActivity.this, true);
                            mAegvChatGroupMember.initData(false, list, adapter);
                            mAegvChatGroupMember.setHandleGridView(ChatGroupDetailActivity.this);
                        } else {
                            if (chatContacts.size() > 0 && chatContacts != null) {
                                adapter1 = new ChatGroupMemberAdapter(ChatGroupDetailActivity.this);
                                adapter1.bindData(chatContacts, "添加");
                                mGvChatGroupMember.setAdapter(adapter1);
                            }
                    }
                    getChatUserInfo(ids.substring(0, ids.length() - 1));

                }
            }.execute();
        }
        if (isCreated)

        {//创建者
            mCreaterMember.setVisibility(View.VISIBLE);
            mNormalMember.setVisibility(View.GONE);
        } else

        {//普通成员
            mNormalMember.setVisibility(View.VISIBLE);
            mCreaterMember.setVisibility(View.GONE);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.chat_group_btn_back:
                finish();
                break;
            case R.id.rl_chat_group_name:
                Intent intent = new Intent(ChatGroupDetailActivity.this, UpdateGroupNameActivity.class);
                intent.putExtra("old_name", mTvChatGroupName.getText().toString());
                startActivityForResult(intent, REQUEST_NEW_GROUP_NAME);
                break;
            case R.id.rl_chat_group_notify:
                mTbChatGroupNotify.toggle();
                break;
            case R.id.rl_chat_group_clear:
                AllDialogUtil dialogUtil = AllDialogUtil.getInstance(ChatGroupDetailActivity.this);
                String okText = this.getString(R.string.clear);
                String cancelText = this.getString(R.string.cancel);
                dialogUtil.titleDeleteMsgStyle(okText, cancelText, "确定清除聊天记录吗？");
                dialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
                    @Override
                    public void onConfirmClick(Dialog lDialog) {
                        if (RongIM.getInstance() != null) {
                            RongIM.getInstance().clearMessages(mConversationType, targetId, new RongIMClient.ResultCallback<Boolean>() {
                                @Override
                                public void onSuccess(Boolean aBoolean) {
                                    Toast.makeText(ChatGroupDetailActivity.this, "聊天记录已清除", Toast.LENGTH_LONG).show();
                                }

                                @Override
                                public void onError(RongIMClient.ErrorCode errorCode) {
                                    Toast.makeText(ChatGroupDetailActivity.this, "清除失败", Toast.LENGTH_LONG).show();
                                }
                            });
                        }

                        lDialog.dismiss();
                    }

                    @Override
                    public void onCancelClick(Dialog lDialog) {
                        lDialog.dismiss();

                    }

                });
                break;
            case R.id.rl_chat_group_dissolve:
                showExitGroupDlg();
                break;
        }
    }

    /**
     * 聊天小组信息
     */
    private void getChatUserInfo(String userIds) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID_OLD, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_ID, loginid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_IDS, userIds));
        ChatUserInfoMsg chatGroupInfoMsg = new ChatUserInfoMsg(mHandler.obtainMessage(MSG_CHAT_USER_INFO), ChatGroupDetailActivity.this);
        chatGroupInfoMsg.mApi = AsynHttpClient.API_RONG_CHAT_USER_INFO;
        chatGroupInfoMsg.type = 1;
        chatGroupInfoMsg.mParams = nvps;
        AsynHttpClient.getInstance(this).execRongHttp(chatGroupInfoMsg);
    }

    /**
     * 退出或解散群组弹框
     */
    public void showExitGroupDlg() {
        AllDialogUtil dialogUtil = AllDialogUtil.getInstance(ChatGroupDetailActivity.this);
        String okText = this.getString(R.string.label_btn_ok);
        String cancelText = this.getString(R.string.cancel);
        if (isSingle) {
            dialogUtil.titleDeleteMsgStyle(okText, cancelText, "删除与此人的所有聊天对话");
        } else {
           /* if ("2".equals(mUserType)) {
                dialogUtil.titleDeleteMsgStyle(okText, cancelText, "解散小组后，组中成员将失去联系");
            } else if ("1".equals(mUserType)) {*/
            dialogUtil.titleDeleteMsgStyle(okText, cancelText, "退出小组后,将不再接收此小组的消息");
            /*}*/
        }
        dialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog) {
                if (isSingle) {
                    RongIM.getInstance().deleteMessages(mConversationType, targetId, new RongIMClient.ResultCallback<Boolean>() {
                        @Override
                        public void onSuccess(Boolean aBoolean) {
                            RongIM.getInstance().removeConversation(mConversationType, targetId);
                            Intent i = new Intent();
                            i.putExtra("disFinish", "disFinish");
                            setResult(112, i);
                            finish();
                        }

                        @Override
                        public void onError(RongIMClient.ErrorCode errorCode) {

                        }
                    });
                } else {
                    RongIM.getInstance().quitDiscussion(targetId, new RongIMClient.OperationCallback() {
                        @Override
                        public void onSuccess() {
                            RongIM.getInstance().removeConversation(mConversationType, targetId);
                            Intent i = new Intent();
                            i.putExtra("disFinish", "disFinish");
                            setResult(112, i);
                            finish();
                        }

                        @Override
                        public void onError(RongIMClient.ErrorCode errorCode) {

                        }
                    });

                }

                lDialog.dismiss();
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();

            }

        });

    }


    @Override
    public void addImage() {
        /*Intent intent = new Intent(ChatGroupDetailActivity.this, ChooseContactByTeamActivity.class);
        intent.setAction("create_chat_group");
        intent.putExtra("chat_group_id", targetId);
        intent.putExtra("chat_group_name", mGroupName);
        intent.putExtra("user_type", mUserType);
        intent.putExtra("is_note", mIsNote);
        startActivity(intent);*/
        Intent intent = new Intent(ChatGroupDetailActivity.this, ChooseContactByTeamActivity.class);
        intent.putExtra("member", mChatContacts);
        intent.setAction("create_chat_group");
        intent.putExtra("isSingle", isSingle);
        intent.putExtra("chat_group_id", targetId);
        startActivityForResult(intent, ADD_MEMBER_REQUEST_CODE);
    }

    @Override
    public void delImage(int position) {
        // removeMemberByChatGroup((String) mAegvChatGroupMember.getData().get(position).get("user_id"));
        RongIMClient.getInstance().removeMemberFromDiscussion(targetId, (String) mAegvChatGroupMember.getData().get(position).get("user_id"), null);
        mChatContacts.remove(position);
        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        for (int i = 0; i < mChatContacts.size(); i++) {
            ChatContact chatContact = mChatContacts.get(i);
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("text", chatContact.getUserName());
            map.put("icon", chatContact.getUserImg());
            map.put("user_id", chatContact.getUserId());
            list.add(map);
        }
        ImageAdapter adapter = new ImageAdapter(ChatGroupDetailActivity.this, true);
        mAegvChatGroupMember.initData(false, list, adapter);
        mAegvChatGroupMember.setHandleGridView(ChatGroupDetailActivity.this);
    }

    @Override
    public void queryImage(int position) {
        if ("0".equals((String) mAegvChatGroupMember.getData().get(position).get("user_id")) || StringUtil.isEmpty((String) mAegvChatGroupMember.getData().get(position).get("user_id"))) {
            Toast.makeText(this, "对不起，该用户未注册", Toast.LENGTH_LONG).show();
        } else {
            Intent intent = new Intent(this, ContactNameCardActivity.class);
            intent.putExtra("user_id", (String) mAegvChatGroupMember.getData().get(position).get("user_id"));
            startActivity(intent);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_NEW_GROUP_NAME:
                    String newName = data.getExtras().getString("new_name");
                    if (!StringUtil.isEmpty(newName)) {
                        mGroupName = newName;
                        RongIM.getInstance().setDiscussionName(targetId, mGroupName, new RongIMClient.OperationCallback() {
                            @Override
                            public void onSuccess() {
                                mTvChatGroupName.setText(mGroupName);
                            }

                            @Override
                            public void onError(RongIMClient.ErrorCode errorCode) {

                            }
                        });

                    }
                    break;
            }
        }
    }

}
